package com.rzjm.api.netty.water.business.inhandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rzjm.api.entity.DeviceWater;
import com.rzjm.api.entity.DeviceWaterUpdateVersion;
import com.rzjm.api.netty.water.NettyUtil;
import com.rzjm.api.netty.water.entity.ReceiveData;
import com.rzjm.api.service.IDeviceWaterMessagesService;
import com.rzjm.api.service.IDeviceWaterService;
import com.rzjm.api.service.IDeviceWaterUpdateVersionService;
import com.rzjm.api.util.ByteUtil;
import com.rzjm.api.util.CRCUtil;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Optional;

import static com.rzjm.api.netty.water.constant.ReceiveTypeEnum.RECEIVE_TYPE_45;

/**
 * @author WangWT
 * @Description: 请求固件包数据
 * @date 2023/4/14 9:27
 */
@Component
public class Receive45InHandler implements InHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(Receive45InHandler.class);

	@Autowired
	private IDeviceWaterService devicesService;
	@Autowired
	private IDeviceWaterMessagesService deviceMessagesService;
	@Autowired
	private IDeviceWaterUpdateVersionService deviceUpdateVersionService;

	@Value("${web.uploadPath}")
	private String uploadPath;

	/**
	 * 设备上报数据中的type
	 */
	public Integer type = RECEIVE_TYPE_45.getType();

	@Override
	public void handler(ChannelHandlerContext ctx, ReceiveData receiveData) {
		//保存Channel
		NettyUtil.addChannel(ctx, receiveData.getId());
		// 保存上报数据日志
		Optional.ofNullable(getMessage(receiveData))
				.ifPresent(message -> deviceMessagesService.save(message));
		DeviceWater devices = devicesService.findById(receiveData.getId());
		if (devices != null) {
			//分包编号
			int packageNo = Integer.parseInt(receiveData.getV1());
			System.out.println("分包编号：" + packageNo);

			DeviceWaterUpdateVersion updateVersion = deviceUpdateVersionService.getOne(Wrappers.<DeviceWaterUpdateVersion>lambdaQuery()
					.eq(DeviceWaterUpdateVersion::getUpdateVersion, devices.getVersion())
					.last("limit 1"));
			if(updateVersion != null){
				System.out.println("更新文件版本： " + updateVersion.getUpdateVersion());
			}
			String filePath = uploadPath + File.separator + updateVersion.getFileUrl();
			ByteBuffer out = ByteBuffer.allocate(1088);

			byte[] fileData;
			try {
				fileData = ByteUtil.fileToByteArray(filePath);
			} catch (IOException e) {
				System.out.println("获取升级文件失败：" + e.getMessage());
				return;
			}
			//报文头
			out.put((byte) 0x7F);
			out.put((byte) 0xC0);
			out.put((byte) 0x00);
			out.put((byte) 0x01);
			//数据长度
			out.put((byte) 0x04);
			out.put((byte) 0x06);
			//固件包数据
			out.put((byte) 0x02);
			//分包编号
			out.put((byte) packageNo);
			//数据域
			byte[] packet = ByteUtil.getPacket(fileData, packageNo, 1024);
			out.put(packet);
			//校验
			out.flip();
			byte[] enBytes = new byte[out.limit()];
			//截取有效报文
			out.get(enBytes);
//            String crc1 = CRCUtil.getCRC(enBytes);
			String crc1 = CRCUtil.calculateCRC16Str(enBytes);
			//完整报文
			String dataStr = ByteUtil.hex2String(enBytes) + crc1;
			//发送
//            reply(dataStr, receiveData.getId());
			reply(ByteUtil.hexStringToByteArray(dataStr), receiveData.getId());
			LOGGER.info("=====>回复给设备当前最新程序包, msg={}", dataStr);
		}

	}
}
